﻿using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.App
{
    /// <summary>
    /// 负责吧请求路由到终结点
    /// </summary>
    public class EndpointRoutingMiddleware : IMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly RouteOptions _options;

        public EndpointRoutingMiddleware(
            RequestDelegate next,
            IOptions<RouteOptions> options)
        {
            _next = next;
            _options = options.Value;
        }

        public async Task Invoke(HttpContext context)
        {
            var endpoint = context.GetEndpoint();
            if (endpoint == null)
            {
                var endpoints = _options.EndpointDataSource.GetEndpoints();
                foreach (var item in endpoints)
                {
                    if (item.Pattern == context.Request.Path)
                    {
                        context.SetEndpoint(item);
                        break;
                    }
                }
            }
            await _next(context);
        }
    }

    public static class RouterMiddlewareExtensions
    {
        /// <summary>
        /// 注册一个用于匹配Endpoint的中间件
        /// </summary>
        /// <param name="builder"></param>
        public static void UseRouting(this IApplicationBuilder builder)
        {
            builder.UseMiddlware<EndpointRoutingMiddleware>();
        }
    }
}
